package services

import (
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"strings"
	"time"

	"github.com/jinzhu/copier"
	"longmen/server/pkg/common/api_models"
)

func (s *Service) GetAuthInfo(user *models_main.User) (*api_models.AuthResp, error) {
	if exist, err := global.BloomExists(global.BLOOM_ID, cast.ToString(user.Id)); err != nil || !exist {
		return nil, errors.New("用户不存在")
	}
	authResp := new(api_models.AuthResp)
	auth, err := db_main.GetUserAuthParam(map[string]interface{}{"uid": user.Id})
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}

	user, err = mysql.GetUserParam(map[string]interface{}{"id": user.Id})

	if user.IsAnchor == 1 && auth.Uid <= 0 {
		authResp.Status = 1 //已通过
		return authResp, err
	}
	// 已认证主播后台取消主播资格时不让开播

	if auth.Uid > 0 && (auth.Status == 1) && //已认证
		user.IsAnchor != 1 {
		authResp.Status = 3
		authResp.Desc = "系统判定该主播为已认证但被取消，请联系管理员"
		return authResp, err
	}
	if auth.Uid > 0 && auth.Status == 2 { //已驳回
		authResp.Status = 2
		authResp.Desc = "申请被驳回"
		return authResp, err
	}
	if auth.Uid <= 0 { //普通用户
		authResp.Status = 3
		return authResp, err
	}
	imgs := strings.Split(auth.IdCardUrl, ",")
	for k, img := range imgs {
		imgs[k] = cache.GetConfigPub().ImgDomain + img
	}
	authResp.Imgs = imgs
	global.Log.Debugf("6GetAuthInfo9%v", authResp.Imgs)
	err = copier.Copy(authResp, auth)

	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return authResp, nil
}

func (s *Service) IdentityAuth(r *api_models.IdentityAuthReq, user *models_main.User) error {
	fName := "IdentityAuth"
	err := s.CheckCode(user.Mobile, r.SmsCode)
	if err != nil {
		return err
	}
	newAuth := &models_main.UserAuth{
		LiveCategories: r.LiveCategories,
		LiveCareer:     r.LiveCareer,
		QQ:             r.QQ,
		WeChat:         r.WeChat,
		Desc:           r.Desc,
		RealName:       r.RealName,
		IdNum:          r.IdNum,
		IdCardUrl:      r.IdCardUrl,
		SubmitTime:     time.Now(),
		Uid:            user.Id,
		Mobile:         r.Mobile,
		Referrer:       r.Referrer,
	}
	auth, err := db_main.GetUserAuthParam(map[string]interface{}{"uid": user.Id})
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if auth.Status == 1 {
		return errors.New(global.Lang.T("has_been_accepted"))
	}
	session := s.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			global.Log.Error("transaction is error recover", fmt.Errorf("JSON: internal error: %v", r))
			session.Rollback()
		}
	}()
	if err := session.Error; err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if auth.Uid > 0 {
		if err := db_main.DeleteUserAuth(session, auth); err != nil {
			session.Rollback()
			return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
	}
	if err := db_main.InsertUserAuth(session, newAuth); err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if err := session.Commit().Error; err != nil {
		return fmt.Errorf("%s %s", util.Convert(fName), err.Error())
	}
	return nil
}
